using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.suppliercontacts;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.suppliercontacts
{
    /// <summary>
    /// 获取供应商联系人列表查询处理器
    /// </summary>
    public class GetSupplierContactsQueryHandler : IRequestHandler<GetSupplierContactsQuery, ApiPaging<SupplierContactListDto>>
    {
        private readonly IBaseRepository<SupplierContact> _supplierContactRepository;
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetSupplierContactsQueryHandler> _logger;

        public GetSupplierContactsQueryHandler(
            IBaseRepository<SupplierContact> supplierContactRepository,
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<GetSupplierContactsQueryHandler> logger)
        {
            _supplierContactRepository = supplierContactRepository;
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取供应商联系人列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<SupplierContactListDto>> Handle(GetSupplierContactsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询供应商联系人列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _supplierContactRepository.GetAll()
                    .Where(sc => !sc.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var supplierContacts = await query
                    .OrderByDescending(sc => sc.CreatedTime) // 按创建时间倒序排列
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 获取供应商信息
                var supplierIds = supplierContacts.Select(sc => sc.SupplierId).Distinct().ToList();
                var suppliers = await _supplierRepository.GetAll()
                    .Where(s => supplierIds.Contains(s.Id) && !s.IsDeleted)
                    .ToDictionaryAsync(s => s.Id, s => s.SupplierName, cancellationToken);

                // 映射到DTO并填充供应商名称
                var supplierContactDtos = new List<SupplierContactListDto>();
                foreach (var contact in supplierContacts)
                {
                    var dto = _mapper.Map<SupplierContactListDto>(contact);
                    dto.SupplierName = suppliers.ContainsKey(contact.SupplierId) ? suppliers[contact.SupplierId] : "未知供应商";
                    supplierContactDtos.Add(dto);
                }

                _logger.LogInformation("成功查询供应商联系人列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, supplierContactDtos.Count);

                return new ApiPaging<SupplierContactListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = supplierContactDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询供应商联系人列表时发生异常");
                
                return new ApiPaging<SupplierContactListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询供应商联系人列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<SupplierContactListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<SupplierContact> ApplyFilters(IQueryable<SupplierContact> query, GetSupplierContactsQuery request)
        {
            // 供应商ID精确查询
            if (request.SupplierId.HasValue)
            {
                query = query.Where(sc => sc.SupplierId == request.SupplierId.Value);
            }

            return query;
        }
    }
} 